<script lang="ts" setup>
import type { SystemMenuApi } from '#/api/system/menu';
import type { SystemTenantPackageApi } from '#/api/system/tenant-package';

import { computed, ref } from 'vue';

import { Tree, useVbenDrawer } from '@vben/common-ui';
import { COMMON_OPT } from '@vben/constants';
import { handleTree } from '@vben/utils';

import { ElMessage } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { getMenuList } from '#/api/system/menu';
import {
  createTenantPackage,
  getTenantPackage,
  updateTenantPackage,
} from '#/api/system/tenant-package';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<SystemTenantPackageApi.TenantPackage>();
const getTitle = computed(() => {
  return formData.value
    ? $t('ui.actionTitle.edit', ['套餐'])
    : $t('ui.actionTitle.create', ['套餐']);
});
const menuTree = ref<SystemMenuApi.SystemMenu[]>([]); // 菜单树
const menuLoading = ref(false); // 加载菜单列表
const loadingMenus = ref(false);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    drawerApi.lock();
    // 提交表单
    const data =
      (await formApi.getValues()) as SystemTenantPackageApi.TenantPackage;
    try {
      // formApi.setFieldValue('menuIds', treeRef.value!.getCheckedKeys(false));
      await (formData.value && formData.value.OPT_TYPE === COMMON_OPT.UPDATE
        ? updateTenantPackage(data)
        : createTenantPackage(data));
      // 关闭并提示
      await drawerApi.close();
      emit('success');
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      drawerApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载菜单列表
    loadingMenus.value = true;
    await loadMenuTree();
    // 加载数据
    const data = drawerApi.getData<SystemTenantPackageApi.TenantPackage>();
    if (!data || !data.id) {
      return;
    }
    drawerApi.lock();
    try {
      formData.value = await getTenantPackage(data.id);
      if (data.OPT_TYPE === COMMON_OPT.COPY) {
        formData.value.id = -1;
      }
      formData.value.OPT_TYPE = data.OPT_TYPE;
      await formApi.setValues(formData.value);
    } finally {
      loadingMenus.value = false;
      drawerApi.unlock();
    }
  },
});

/** 加载菜单树 */
async function loadMenuTree() {
  menuLoading.value = true;
  try {
    const data = await getMenuList();
    menuTree.value = handleTree(data) as SystemMenuApi.SystemMenu[];
  } finally {
    menuLoading.value = false;
  }
}
</script>

<template>
  <Drawer :title="getTitle" class="w-2/5">
    <Form class="mx-6">
      <template #menuIds="slotProps">
        <Tree
          class="max-h-96 overflow-y-auto"
          :tree-data="menuTree"
          multiple
          bordered
          v-bind="slotProps"
          value-field="id"
          label-field="meta.title"
        />
      </template>
    </Form>
  </Drawer>
</template>

<style scoped>
.min-h-200px {
  min-height: 200px;
}
</style>
